/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entity;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Persistence;
import javax.persistence.Query;
import jpa.exceptions.NonexistentEntityException;

/**
 *
 * @author Aditya-Z
 */
public class KelolaAkun {
    
    public KelolaAkun() {
        emf = Persistence.createEntityManagerFactory("Dokter_mandiriPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void createAkun(Akun akun) {
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        try {
            em.persist(akun);
            em.getTransaction().commit();
        } catch (Exception e) {
            em.getTransaction().rollback();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
    public Akun getAkun(String username) {
        Akun akun = null;
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT object(a) FROM Akun AS a WHERE a.username=:usr");
            q.setParameter("usr", username);
            akun = (Akun) q.getSingleResult();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return akun;
    }
    public boolean checkAkun(String username) {
        boolean result = false;
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT count(o) FROM Akun AS o WHERE o.username=:usr");
            q.setParameter("usr", username);
            int jumlahUser = ((Long) q.getSingleResult()).intValue();
            if (jumlahUser > 0) {
                result = true;
            }
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return result;
    }
     public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Akun akun;
            try {
                akun = em.getReference(Akun.class, id);
                akun.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The user with id " + id+ " no longer exists.", enfe);
            }
            em.remove(akun);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }}

        }


 

